package cn.itcast.service.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.Menu;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import cn.itcast.utils.MD5Utils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@Service
public class UserServiceImpl implements UserService {



    @Autowired
    private UserDao userDao;

    @Override
    public PageResult findUser(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.findAllUserByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void updateUser(Integer[] roleIds, User user) {
        //修改到用户表
        userDao.updateUser(user);
        //先将用户角色表相关数据删除
        userDao.deleteUserAndRole(user.getId());
        //修改用户角色表
        if (roleIds!=null&&roleIds.length>0){
            for (Integer roleId : roleIds) {
                userDao.addUserAndRole(user.getId(),roleId);
            }
        }
    }

    @Override
    public void addUser(Integer[] roleIds, User user) {
        //添加到用户表
        userDao.addUser(user);
        //添加到用户角色表
        if (roleIds!=null&&roleIds.length>0){
            for (Integer roleId : roleIds) {
                userDao.addUserAndRole(user.getId(),roleId);
            }
        }
    }

    @Override
    public User findOneUser(Integer userId) {
        //TODO 密码显示 是否需要解析
        return userDao.findUserById(userId);
    }

    @Override
    public boolean deleteUserById(Integer id) {
        //删除之前判断该数据是否与其他数据关联
        if (userDao.findRoleByUserId(id)==0){
            return userDao.deleteUserById(id)>0;
        }
        return false;
    }

    @Override
    public User loadUserByUsername(String username) {
        return userDao.findUserByUsername(username);
    }

    @Override
    public List<Menu> findMenuByUsername(String username) {
        Page<Menu> page = userDao.findUserMenuByUsername(username);
        return page.getResult();
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }
}
